package de.rs.espresso;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class SISstarter {
	private static String sisPath = "C:\\Users\\Jan\\Downloads\\blif\\mvsis.exe";

	private static String verifyPath = "C:\\Users\\Jan\\Downloads\\blif\\";

	public static void main(String[] args) {

		long startTime = System.currentTimeMillis();
		
		try {
			File path = new File(verifyPath);
			


			for (String s : path.list()) {
				File f = new File(path.getAbsolutePath() + "/" + s);
				if (f.isFile() && s.endsWith(".blif")
						&& !s.endsWith("_sis.blif") && !s.endsWith("_minimized.blif")) {
					

					String name = s.substring(0, s.lastIndexOf('.'));
					
					//System.out.println("Process "+name+"...");
					


					//p.waitFor();
					

					ProcessBuilder builder = new ProcessBuilder(sisPath); 
					builder.directory(path);
					Process p;

					p = builder.start();
					
					OutputStream outputstream = p.getOutputStream();
					PrintWriter writer = new PrintWriter(outputstream);
				
					writer.println("read_blif_mv "+name+".blif");
					writer.println("simplify -m espresso");
					writer.println("write_blif_mv "+name+"_sis.blif");
					writer.println("print_stats");

					
					writer.println("quit");
					writer.flush();
					
					Scanner scanner = new Scanner(p.getInputStream());
					scanner.useDelimiter("\\n");

					while(scanner.hasNextLine()) {
						String line = scanner.nextLine();
						if(line.contains("cube = ")) {
							String cubes = line.substring(line.indexOf("cube = ")+7,line.indexOf("ff-lit", line.indexOf("cube = ")+7)-1);
							System.out.println( String.format("%-"+30+"s","Result for "+name+".blif: " )  + String.format("%-"+7+"s",cubes ));
						}
					}
					


					scanner.close();
					p.destroy();

				}
			}
			


		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		long endTime = System.currentTimeMillis();
		
		System.out.println("runtime: "+(endTime-startTime)+"ms");

		System.exit(0);
	}
}
